<template>
  <el-dialog
      :title="state.type == 'add' ? '添加分类' : '修改分类'"
      v-model="state.visible"
      width="600px"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="分类名" prop="categoryName">
        <el-input type="text" v-model="state.ruleForm.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="分类级别" prop="level">
        <el-select
            v-model="one"
            :empty-values="[null, undefined]"
            :value-on-clear="null"
            clearable
            placeholder="Select"
            style="width: 120px;margin-left: 10px"
        >
          <el-option
              v-for="item in oneOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
          />
        </el-select>
        <el-select
            v-model="two"
            :empty-values="[null, undefined]"
            :value-on-clear="null"
            clearable
            :disabled="one == null"
            placeholder="Select"
            style="width: 120px;margin-left: 10px"
        >
          <el-option
              v-for="item in twoOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
          />
        </el-select>
      </el-form-item>


    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import axios from '@/utils/axios'
import {ElMessage} from 'element-plus'
import {categoryAdd, fetchSecondLevel, fetchThirdLevel, getAllFirstLevel} from "@/api/drugCategory";

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})

// 设置三个等级的值
const one = ref()
const two = ref()

const oneOptions = ref([])
const twoOptions = ref([])

const formRef = ref(null)
const route = useRoute()
const state = reactive({
  visible: false,
  ruleForm: {
    categoryName: '',
    parentId: '',
    grandParentId: ''
  },
  rules: {
    categoryName: [
      {required: 'true', message: '名称不能为空', trigger: ['change']}
    ]
  },
  id: ''
})

// 监听one的变化
watch(one, (newVal) => {
  if (newVal) {
    // 当one变化时，执行的方法
    console.log('one changed:', newVal);
    // 例如：获取二级分类数据
    fetchSecondLevel({
      parentId: newVal,
    }).then((res) => {
      twoOptions.value = res.data.data
    });
  }
});

// 监听two的变化
watch(two, (newVal) => {
  if (newVal) {
    // 当two变化时，执行的方法
    console.log('two changed:', newVal);
    // 例如：获取三级分类数据
  }
});


onMounted(async () => {
  // 获取第一级别分类

})
// 获取详情
const getDetail = (id) => {

}

// 开启弹窗
const open = async (id) => {
  state.visible = true
  await getAllFirstLevel().then((res) => {
    oneOptions.value = res.data.data
  })
  if (id) {
    state.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
  }
}
// 关闭弹窗
const close = () => {
  state.visible = false
  state.ruleForm = {
    categoryName: '',
    parentId: '',
    grandParentId: ''
  }
  one.value = null
  two.value = null
  oneOptions.value = []
  twoOptions.value = []

}
const submitForm = async () => {
  if (state.ruleForm.categoryName == '') {
    ElMessage.error('请输入分类名')
    return
  }
  if (one.value == null && two.value == null) {
    await categoryAdd({
      categoryName: state.ruleForm.categoryName,
      parentId: null,
      grandParentId: null
    })
  } else if (one.value != null && two.value == null) {
    await categoryAdd({
      categoryName: state.ruleForm.categoryName,
      parentId: one.value,
      grandParentId: null
    })
  } else if (one.value != null && two.value != null) {
    await categoryAdd({
      categoryName: state.ruleForm.categoryName,
      parentId: two.value,
      grandParentId: one.value
    })
  }
  if (props.reload) props.reload();
  close()
}
defineExpose({open, close})
</script>